import java.util.LinkedList;

/*
 * @lc app=leetcode.cn id=101 lang=java
 *
 * [101] 对称二叉树
 *
 * https://leetcode-cn.com/problems/symmetric-tree/description/
 *
 * algorithms
 * Easy (45.02%)
 * Total Accepted:    22K
 * Total Submissions: 48.9K
 * Testcase Example:  '[1,2,2,3,4,4,3]'
 *
 * 给定一个二叉树，检查它是否是镜像对称的。
 * 
 * 例如，二叉树 [1,2,2,3,4,4,3] 是对称的。
 * 
 * ⁠   1
 * ⁠  / \
 * ⁠ 2   2
 * ⁠/ \ / \
 * 3  4 4  3
 * 
 * 
 * 但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:
 * 
 * ⁠   1
 * ⁠  / \
 * ⁠ 2   2
 * ⁠  \   \
 * ⁠  3    3
 * 
 * 
 * 说明:
 * 
 * 如果你可以运用递归和迭代两种方法解决这个问题，会很加分。
 * 
 */
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {

    // 递归
    private boolean recursionIsSymmetric(TreeNode a, TreeNode b) {
        if (a != null && b != null && a.val == b.val) {
            return recursionIsSymmetric(a.left, b.right)
                && recursionIsSymmetric(a.right, b.left);
        } else if (a == null && b == null) {
            return true;
        } else {
            return false;
        }
    }

    // 迭代
    private boolean iterationIsSymmetric(TreeNode a, TreeNode b) {
        LinkedList<TreeNode> aQueue = new LinkedList<>();
        LinkedList<TreeNode> bQueue = new LinkedList<>();
        aQueue.add(a);
        bQueue.add(b);
        boolean answer = true;
        while (answer && !aQueue.isEmpty() && !bQueue.isEmpty()) {
            TreeNode x = aQueue.pop();
            TreeNode y = bQueue.pop();
            if (x != null && y != null && x.val == y.val) {
                aQueue.add(x.left);
                aQueue.add(x.right);
                bQueue.add(y.right);
                bQueue.add(y.left);
            } else if (x == null && y == null) {
                continue;
            } else {
                answer = false;
            }
        }
        return answer;
    }

    public boolean isSymmetric(TreeNode root) {
        if (root == null) {
            return true;
        }
        // return recursionIsSymmetric(root.left, root.right);
        return iterationIsSymmetric(root.left, root.right);
    }
}

